#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "globalarray.h"
#include "globalstyle.h"

#include <QMessageBox>
#include <QList>
#include <QString>
#include <QPushButton>
#include <QDebug>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QComboBox>
#include <QTimer>
#include <QTextStream>
#include <QTextCodec>
#include <QVector>
#include <QShortcut>
#include <QHotkey>
#include <QBitmap>
#include <QFont>
#include <QButtonGroup>
#include <QSound>
#include <QDesktopServices>
#include <QClipboard>
#include <QMediaPlayer>
#include <QColor>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(TITLE);
    windowBeautify();
    //用来处理鼠标点击坐标的定时器
    posTimer = new QTimer(this);
    //用来进行ocr并更新文字数组的定时器
    ocrTimer = new QTimer(this);
    aliyuntts = new AliyunTts;
    player = new QMediaPlayer;
    aidialog = new AiDialog(this);
    recorder =  new QAudioRecorder(this);
    dialog = new CustomDialog(this);
    logo = new AudioLogo(this);
    // 语音助手
    audioTimer = new QTimer;
    audioTimer->setInterval(5000);

    if(recorder->defaultAudioInput().isEmpty())
    {
        return; //无音频录入设备
    }

    //tolerance = 0.99; // 容忍值,粗略忽略鼠标的位置不同导致的影响
    //测试容忍值的临界值
    tolerance = 0.99;
    cutimage = new CutImage();
    //安装事件过滤器
    installEventFilter(this);
    installFilter();

    //Python C API
    setenv("PYTHONHOME", "/home/mhc/anaconda3/envs/modelscope", 1);
    setenv("LD_LIBRARY_PATH", "/home/mhc/anaconda3/envs/modelscope/lib", 1);
    Py_Initialize();

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.argv = ['python.py']");
    PyRun_SimpleString("sys.path.append('./')");
    //导入模块
    importPythonModules();
    //导入方法
    importPythonFunctions();

    //导入模型
    PyObject_CallFunction(pDeteImport,NULL);
    PyObject_CallFunction(pRecoImport,NULL);
    PyObject_CallFunction(pAudioImport, NULL);

    //解决奇怪的bug
    audioRecorder();
    recorder->stop();

    // 创建全局快捷键实例
    magnifierKey = new QHotkey(QKeySequence("Ctrl+M"), true, this);
    normalizeKey = new QHotkey(QKeySequence("Ctrl+Shift+M"), true, this);
    startKey = new QHotkey(QKeySequence("Ctrl+Alt+C"), true, this);
    quitKey = new QHotkey(QKeySequence("Ctrl+T"), true, this);
    showtextfierKey = new QHotkey(QKeySequence("Ctrl+K"), true, this);
    copyKey = new QHotkey(QKeySequence("Ctrl+L"), true, this);
    AiKey = new QHotkey(QKeySequence("Ctrl+A+I"), true, this);
    //预处理
    preHandleTimer = new QTimer(this);
    //preHandleTimer->start(6000);

    // 将子页面添加到QStackedWidget中
    ui->pages->addWidget(ui->page_home);
    ui->pages->addWidget(ui->page_voice);
    ui->pages->addWidget(ui->page_shortcut);
    ui->pages->addWidget(ui->page_settings);
    ui->pages->addWidget(ui->page_generate);
    ui->pages->addWidget(ui->page_tools);
    ui->pages->addWidget(ui->page_recognize);
    speakText("欢迎使用麒麟颂语软件");
    setPyttsx3ComboBox();
    initializeWindow();

    // 将所有的喇叭图标放入List中
    audioLogoList<<ui->play_language<<ui->play_voice<<ui->play_changeTheme<< ui->play_start<<ui->play_quit<<ui->play_menuItem1<<ui->play_menuItem2<<ui->play_menuItem3<<ui->play_menuItem4<<ui->play_menuItem5
                <<ui->play_menuItem6<<ui->play_shortcut1<<ui->play_shortcut2<<ui->play_voicedescription<<ui->play_microsoft<<ui->play_google<<ui->play_engine<<ui->Audio1<<ui->Audio2<<ui->Audio3<<ui->Audio4
               <<ui->Audio5<<ui->Audio6<<ui->Audio7<<ui->Audio8<<ui->Audio9<<ui->Audio11<<ui->Audio12<<ui->Audio13;;

    // 默认显示第一个子页面
    ui->pages->setCurrentIndex(0);
    logo->show();
    // 让主界面在屏幕中心出现
    QScreen *primaryScreen = QGuiApplication::primaryScreen();
    // 获取屏幕的尺寸
    QSize screenSize = primaryScreen->size();
    this->move(screenSize.width()/2 - this->size().width()/2, screenSize.height()/2 - this->size().height()/2);
    // 规范小麒麟图标的出现位置
    logo->move(screenSize.width()/2 + this->size().width()/2, screenSize.height()/2 - logo->size().height()/2);
}

//初始化设置
void MainWindow::initializeWindow()
{
    // 创建一个QFile对象并打开文本文件
    QFile file("/home/mhc/settings.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件";
    }
    int lineNumber = 0,themeStyle,ttsStyle,voiceStyle,rateValue,pitchValue,audioStyle,fontStyle;
    QString path;
    qreal zoomFactor;
    // 创建一个QTextStream对象并关联到文件
    QTextStream in(&file);

    // 逐行读取文本文件内容
    while (!in.atEnd()) {
        lineNumber++;

        if (lineNumber == 1) {
            themeStyle = in.readLine().toInt();
        } else if (lineNumber == 2) {
            ttsStyle = in.readLine().toInt();
        } else if (lineNumber == 3) {
            voiceStyle = in.readLine().toInt();
        } else if (lineNumber == 4) {
            rateValue = in.readLine().toInt();
        } else if (lineNumber == 5) {
            pitchValue = in.readLine().toInt();
        } else if (lineNumber == 6) {
            audioStyle = in.readLine().toInt();
        } else if (lineNumber == 7) {
            fontStyle = in.readLine().toInt();
            fontSize = fontStyle;
        } else if (lineNumber == 8) {
            path = in.readLine();
        } else if (lineNumber == 9) {
            zoomFactor = in.readLine().toInt();
        }
    }
    // 关闭文件
    file.close();

    isTextWindowEnabled = false;
    //语音提示功能
    if (!audioStyle)
        on_setPlayInvisible_clicked();
    else
        on_setPlayVisible_clicked();
    //设置声音引擎，设置声音类型
    if (ttsStyle == 1)
    {
        ui->label_engine->setText("pyttsx3");
        ui->comboBox_pyttsx3->setCurrentIndex(voiceStyle);
        ui->radioButton_pytts->setChecked(true);
        ui->label_voice->setText(ui->comboBox_pyttsx3->currentText());
    } else if (ttsStyle == 2) {
        ui->label_engine->setText("微软");
        onvoicechange(voiceStyle);
        ui->comboBox_microsoft->setCurrentIndex(voiceStyle);
        ui->radioButton_microsoft->setChecked(true);
        ui->label_voice->setText(ui->comboBox_microsoft->currentText());
    } else if (ttsStyle == 3) {
        ui->label_engine->setText("谷歌");
        ui->comboBox_google->setCurrentIndex(voiceStyle);
        ui->radioButton_google->setChecked(true);
        ui->label_voice->setText(ui->comboBox_google->currentText());
    } else if (ttsStyle == 4) {
        ui->label_engine->setText("百度");
        ui->comboBox_baidu->setCurrentIndex(voiceStyle);
        ui->radioButton_baidu->setChecked(true);
        ui->label_voice->setText(ui->comboBox_baidu->currentText());
    } else if (ttsStyle == 5) {
        ui->label_engine->setText("阿里云");
        ui->comboBox_aliyun->setCurrentIndex(voiceStyle);
        ui->radioButton_aliyun->setChecked(true);
        ui->label_voice->setText(ui->comboBox_aliyun->currentText());
    }

    updateratevalue(rateValue);
    updatepitchvalue(pitchValue);

    QString styleSheet = GlobalStyle::getInstance().getStyle(themeStyle, fontStyle);
    MainWindow::setStyleSheet(styleSheet);

    ui->slider_rate->setValue(rateValue);
    ui->slider_pitch->setValue(pitchValue);
    ui->audioPath->setText(path);

    ui->baidu_rate->setValue(30);
    ui->baidu_pitch->setValue(30);
    ui->baidu_volume->setValue(50);
    ui->aliyun_rate->setValue(50);
    ui->aliyun_pitch->setValue(50);
    ui->aliyun_volume->setValue(50);

    menuIcon();
    showTextBox();
    playAudio();
    connectSlots();
    updateLabelValue();
}
//根据当前环境下已有的引擎中的声音列表来设置comboBox
void MainWindow::setPyttsx3ComboBox()
{
    PyObject* pResult = PyObject_CallObject(setPyttsx3,NULL);
    if(pResult) {
        //将返回值转化为string类型
        PyObject* repr = PyObject_Repr(pResult);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
        QString result = PyBytes_AsString(str);
        QList<QString> stringList = result.mid(1, result.length() - 2).split("-");
        foreach (const QString &str, stringList) {
            ui->comboBox_pyttsx3->addItem(str);
        }
        Py_XDECREF(pResult);  // 释放Python对象
    } else {
        PyErr_Print();
    }
}
//手动实现界面随着鼠标的拖动而移动
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        lastMousePosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        move(event->globalPos() - lastMousePosition);
        event->accept();
    }
}

//pythonAPI function: 将连接槽函数的操作集成在一起a
void MainWindow::connectSlots()
{
    // 界面变化和鼠标位置
    connect(posTimer, &QTimer::timeout, this, &MainWindow::mouseInText);
    connect(ocrTimer, &QTimer::timeout, this, &MainWindow::handleImgChange);
    // 连接快捷键触发的槽函数
    connect(magnifierKey, &QHotkey::activated, this, &MainWindow::magnifierWindowSlot);
    connect(normalizeKey, &QHotkey::activated, this, &MainWindow::normalizeWindow);
    connect(startKey, &QHotkey::activated, this, &MainWindow::hotkeyStart);
    connect(quitKey, &QHotkey::activated, this, &MainWindow::hotkeyQuit);
    connect(showtextfierKey, &QHotkey::activated, this, &MainWindow::showTextWindowSlots);
    connect(copyKey, &QHotkey::activated, this, &MainWindow::copyNowText);
    connect(AiKey, &QHotkey::activated, this, &MainWindow::hotkeyAi);
    // 连接 QSlider 的 valueChanged 信号到槽函数来更新 QLabel 的值
    connect(ui->slider_rate, SIGNAL(valueChanged(int)), this, SLOT(updateratevalue(int)));
    connect(ui->slider_pitch, SIGNAL(valueChanged(int)), this, SLOT(updatepitchvalue(int)));
    connect(ui->magnifierSlider, SIGNAL(valueChanged(int)), this, SLOT(updatezoomvalue(int)));
    connect(ui->menuList, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(menulistItemChanged(QListWidgetItem*, QListWidgetItem*)));
    // 将QListWidget的currentRowChanged信号连接到槽函数on_menuList_currentRowChanged
    connect(ui->menuList, SIGNAL(currentRowChanged(int)), this, SLOT(on_menuList_currentRowChanged(int)));
    //tts
    connect(ui->slider_pitch, &QSlider::valueChanged, this, &MainWindow::setPitch);
    connect(ui->slider_rate, &QSlider::valueChanged, this, &MainWindow::setRate);
    connect(ui->comboBox_microsoft, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MainWindow::onvoicechange);
    connect(preHandleTimer, &QTimer::timeout, this, &MainWindow::preHandle);
    //界面切换的槽函数
    connect(ui->comboBoxStyle, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxIndexChanged(int)));
    //tts-version
    connect(ui->radioButton_pytts,SIGNAL(toggled(bool)),this,SLOT(checkSlot1(bool)));
    connect(ui->radioButton_microsoft,SIGNAL(toggled(bool)),this,SLOT(checkSlot2(bool)));
    connect(ui->radioButton_google,SIGNAL(toggled(bool)),this,SLOT(checkSlot3(bool)));
    connect(ui->radioButton_baidu,SIGNAL(toggled(bool)),this,SLOT(checkSlot4(bool)));
    connect(ui->radioButton_aliyun,SIGNAL(toggled(bool)),this,SLOT(checkSlot5(bool)));
    //自定义的信号，用来人工智能的录音功能
    connect(aidialog, &AiDialog::labelClicked, this, &MainWindow::audioRecorder);
    connect(aidialog, &AiDialog::labelReleased, this, &MainWindow::stopRecorder);
    connect(aidialog, &AiDialog::labelHover, this, &MainWindow::speakAiAnswer);
    //语音助手
    connect(logo, &AudioLogo::startAssistant, this, &MainWindow::startAssistant);
    connect(dialog, &CustomDialog::quitDialog, this, &MainWindow::stopTimer);
    connect(audioTimer, &QTimer::timeout, this, &MainWindow::audioAssistant);
    //连接自定义的信号和槽
    connect(dialog, &CustomDialog::call, this, &MainWindow::call);
    connect(dialog, &CustomDialog::myStart, this, &MainWindow::on_btnStart_clicked);
    connect(dialog, &CustomDialog::myQuit, this, &MainWindow::on_btnCancel_clicked);
    connect(dialog, &CustomDialog::changeTheme, this, &MainWindow::changeThemeToBw);
    connect(dialog, &CustomDialog::chooseM, this, &MainWindow::myCheckSlot1);
    connect(dialog, &CustomDialog::chooseG, this, &MainWindow::myCheckSlot2);
    connect(dialog, &CustomDialog::chooseP, this, &MainWindow::myCheckSlot3);
    connect(dialog, &CustomDialog::chooseB, this, &MainWindow::myCheckSlot4);
    connect(dialog, &CustomDialog::chooseA, this, &MainWindow::myCheckSlot5);
    connect(dialog, &CustomDialog::startAudio, this, &MainWindow::on_setPlayVisible_clicked);
    connect(dialog, &CustomDialog::stopAudio, this, &MainWindow::on_setPlayInvisible_clicked);
    connect(dialog, &CustomDialog::smallSizeFont, this, &MainWindow::on_setSmallFont_clicked);
    connect(dialog, &CustomDialog::mediumSizeFont, this, &MainWindow::on_setMiddleFont_clicked);
    connect(dialog, &CustomDialog::bigSizeFont, this, &MainWindow::on_setBigFont_clicked);
    connect(dialog, &CustomDialog::rememberSettings, this, &MainWindow::on_rememberSettings_clicked);
    connect(dialog, &CustomDialog::recoverSettings, this, &MainWindow::on_defaultSettings_clicked);
    connect(dialog, &CustomDialog::showText, this, &MainWindow::showTextWindowSlots);
    connect(dialog, &CustomDialog::hideText, this, &MainWindow::showTextWindowSlots);
    connect(dialog, &CustomDialog::magnifier, this, &MainWindow::magnifierWindowSlot);
    connect(dialog, &CustomDialog::dMagnifier, this, &MainWindow::magnifierWindowSlot);
    //connect(dialog, &CustomDialog::bigMagnifier, this, &MainWindow::bigMagnifier);
    //connect(dialog, &CustomDialog::smallMagnifier, this, &MainWindow::smallMagnifier);
    connect(dialog, &CustomDialog::startAi, this, &MainWindow::on_startAi_clicked);
    connect(dialog, &CustomDialog::stopAi, this, &MainWindow::stopAi);
    connect(dialog, &CustomDialog::changeMouse, this, &MainWindow::on_changeCursor_clicked);
}

//pythonAPI function: 保存音频文件
void MainWindow::generateAudio(QString text, QString path)
{
    PyObject* arg1 = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    PyObject* arg2 = PyUnicode_DecodeUTF8(path.toUtf8().constData(), strlen(path.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(2, arg1, arg2);

    PyObject_CallObject(generateMp3, args);
    Py_DECREF(args);
}

//style function: 美化界面
void MainWindow::windowBeautify()
{
    //设置透明度
    setWindowOpacity(0.9);
    //取消标题栏
    setWindowFlags(Qt::FramelessWindowHint);
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);
    //设置圆角
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.drawRoundedRect(bmp.rect(),20,20);//像素为10的圆角
    setMask(bmp);
    // 为窗口添加鼠标事件处理,因为取消了标题栏，所以自己重写界面移动逻辑
    setMouseTracking(true);
}

//style function: 给菜单栏的每项添加图标
void MainWindow::menuIcon()
{
    QListWidgetItem *item1 = ui->menuList->item(0); // 通过行号获取项
    if (item1) {
        QIcon icon1(":/icons/images/home.png");
        item1->setIcon(icon1);
    }
    QListWidgetItem *item2 = ui->menuList->item(1); // 通过行号获取项
    if (item2) {
        QIcon icon2(":/icons/images/person.png");
        item2->setIcon(icon2);
    }
    QListWidgetItem *item3 = ui->menuList->item(2); // 通过行号获取项
    if (item3) {
        QIcon icon3(":/icons/images/shortcut.png");
        item3->setIcon(icon3);
    }
    QListWidgetItem *item4 = ui->menuList->item(3); // 通过行号获取项
    if (item4) {
        QIcon icon4(":/icons/images/settings.png");
        item4->setIcon(icon4);
    }
    QListWidgetItem *item5 = ui->menuList->item(4); // 通过行号获取项
    if (item5) {
        QIcon icon5(":/icons/images/generate.png");
        item5->setIcon(icon5);
    }
    QListWidgetItem *item6 = ui->menuList->item(5); // 通过行号获取项
    if (item6) {
        QIcon icon6(":/icons/images/tools.png");
        item6->setIcon(icon6);
    }
    QListWidgetItem *item7 = ui->menuList->item(6); // 通过行号获取项
    if (item7) {
        QIcon icon7(":/icons/images/audio.png");
        item7->setIcon(icon7);
    }
}

//style function:小喇叭
void MainWindow::playAudio()
{
    //小喇叭图标用来提供语音提示
    QPixmap originalPixmapPlay(":/icons/images/play.png");
    // 调整图片尺寸
    int widthp = 40; // 设置新的宽度
    int heightp = 40; // 设置新的高度
    QPixmap scaledPixmap2 = originalPixmapPlay.scaled(widthp, heightp, Qt::KeepAspectRatio);
    QPalette palette2;
    palette2.setBrush(QPalette::Background, scaledPixmap2);
    foreach (QLabel *label, audioLogoList) {
        label->setAutoFillBackground(true);
        label->setPalette(palette2);
        // 测试用
        label->setVisible(false);
    }
}

//style function:为其他的标签添加图标
void MainWindow::showTextBox()
{
    //添加软件图标
    QLabel *logo = ui->appLogo;
    QPixmap appPixmap(":/icons/images/app.png");
    // 调整图片尺寸
    int widthApp = 90; // 设置新的宽度
    int heightApp = 90; // 设置新的高度
    QPixmap scaledPixmapApp = appPixmap.scaled(widthApp, heightApp, Qt::KeepAspectRatio);
    QPalette paletteApp;
    paletteApp.setBrush(QPalette::Background, scaledPixmapApp);
    logo->setAutoFillBackground(true);
    logo->setPalette(paletteApp);

    //标题艺术字
    QLabel *title = ui->label_title;
    QPixmap titlePixmap(":/icons/images/title.png"); // 替换为你的图片路径
    // 调整图片尺寸
    int widthT = 190; // 设置新的宽度
    int heightT = 60; // 设置新的高度
    QPixmap scaledPixmapT = titlePixmap.scaled(widthT, heightT, Qt::KeepAspectRatio);
    QPalette paletteT;
    paletteT.setBrush(QPalette::Background, scaledPixmapT);
    title->setAutoFillBackground(true);
    title->setPalette(paletteT);

    //首页界面添加书签图标
    QPixmap itemPixmap(":/icons/images/item1.png"); // 替换为你的图片路径
    // 调整图片尺寸
    int widthI = 30; // 设置新的宽度
    int heightI = 30; // 设置新的高度
    QPixmap scaledPixmapI = itemPixmap.scaled(widthI, heightI, Qt::KeepAspectRatio);
    QPalette paletteI;
    paletteI.setBrush(QPalette::Background, scaledPixmapI);
    QList<QLabel *> labelList;
    labelList << ui->item1 << ui->item2 << ui->item3 << ui->item4;
    foreach (QLabel *label, labelList) {
        label->setAutoFillBackground(true);
        label->setPalette(paletteI);
    }

    //首页界面添加标签图标
    /*QPixmap labelPixmap(":/icons/images/llabel.png"); // 替换为你的图片路径
    // 调整图片尺寸
    int widthl = 500; // 设置新的宽度
    int heightl = 64; // 设置新的高度
    QPixmap scaledPixmapl = labelPixmap.scaled(widthl, heightl, Qt::KeepAspectRatio);
    QPalette palettel;
    paletteI.setBrush(QPalette::Background, scaledPixmapl);
    QList<QLabel *> labelListl;
    labelListl << ui->label_language << ui->label_voice << ui->label_engine;
    foreach (QLabel *label, labelListl) {
        label->setAutoFillBackground(true);
        label->setPalette(paletteI);
    }*/

    //声音选择界面中pyttsx3,微软和谷歌的图标
    QLabel *microsoft = ui->micosoftIcon;
    QLabel *google = ui->googleIcon;
    QLabel *python = ui->pythonIcon;
    QLabel *baidu = ui->baiduIcon;
    QLabel *aliyun = ui->aliyunIcon;
    QPixmap microPixmap(":/icons/images/microsoft.png");
    QPixmap googlePixmap(":/icons/images/google.png");
    QPixmap pythonPixmap(":/icons/images/python.png");
    QPixmap baiduPixmap(":/icons/images/baidu.png");
    QPixmap aliyunPixmap(":/icons/images/aliyun.png");
    int width2 = 50;
    int height2 = 50;
    int widthp = 60;
    int heightp = 60;
    int widtha = 56;
    int heighta = 70;
    QPixmap scaledPixmap1 = microPixmap.scaled(width2, height2, Qt::KeepAspectRatio);
    QPixmap scaledPixmap2 = googlePixmap.scaled(width2, height2, Qt::KeepAspectRatio);
    QPixmap scaledPixmap3 = pythonPixmap.scaled(widthp, heightp, Qt::KeepAspectRatio);
    QPixmap scaledPixmapb = baiduPixmap.scaled(width2, height2, Qt::KeepAspectRatio);
    QPixmap scaledPixmapa = aliyunPixmap.scaled(widtha, heighta, Qt::KeepAspectRatio);
    QPalette palette1;
    QPalette palette2;
    QPalette palettep;
    QPalette paletteb;
    QPalette palettea;
    palette1.setBrush(QPalette::Background, scaledPixmap1);
    palette2.setBrush(QPalette::Background, scaledPixmap2);
    palettep.setBrush(QPalette::Background, scaledPixmap3);
    paletteb.setBrush(QPalette::Background, scaledPixmapb);
    palettea.setBrush(QPalette::Background, scaledPixmapa);
    microsoft->setAutoFillBackground(true);
    google->setAutoFillBackground(true);
    python->setAutoFillBackground(true);
    baidu->setAutoFillBackground(true);
    aliyun->setAutoFillBackground(true);
    microsoft->setPalette(palette1);
    google->setPalette(palette2);
    python->setPalette(palettep);
    baidu->setPalette(paletteb);
    aliyun->setPalette(palettea);

    //声音选择界面中聊天框的图标
    QLabel *voiceDesc = ui->voiceDescription;
    QPixmap descPixmap(":/icons/images/chat.png");
    int width3 = 320;
    int height3 = 200;
    QPixmap scaledPixmapDesc = descPixmap.scaled(width3, height3, Qt::KeepAspectRatio);
    QPalette palette3;
    palette3.setBrush(QPalette::Background, scaledPixmapDesc);
    voiceDesc->setAutoFillBackground(true);
    voiceDesc->setPalette(palette3);

    //快捷键说明界面
    QPixmap llPixmap(":/icons/images/longLabel.png");
    int widthll = 220;
    int heightll = 80;
    QPixmap scaledPixmapll = llPixmap.scaled(widthll, heightll, Qt::KeepAspectRatio);
    QPalette palettell;
    palettell.setBrush(QPalette::Background, scaledPixmapll);
    QList<QLabel *> labelListll;
    labelListll << ui->label_shortcut1 << ui->label_shortcut2 << ui->label_shortcut3 << ui->label_shortcut4 << ui->label_shortcut5 << ui->label_shortcut6 << ui->label_shortcut7;
    foreach (QLabel *label, labelListll) {
        label->setAutoFillBackground(true);
        label->setPalette(palettell);
    }

}
//style function:给放大后的界面标签添加图标
void MainWindow::showBigTextBox()
{
    //添加软件图标
    QLabel *logo = ui->appLogo;
    QPixmap appPixmap(":/icons/images/app.png");
    // 调整图片尺寸
    int widthApp = 135; // 设置新的宽度
    int heightApp = 135; // 设置新的高度
    QPixmap scaledPixmapApp = appPixmap.scaled(widthApp, heightApp, Qt::KeepAspectRatio);
    QPalette paletteApp;
    paletteApp.setBrush(QPalette::Background, scaledPixmapApp);
    logo->setAutoFillBackground(true);
    logo->setPalette(paletteApp);

    //标题艺术字
    QLabel *title = ui->label_title;
    QPixmap titlePixmap(":/icons/images/title.png"); // 替换为你的图片路径
    // 调整图片尺寸
    int widthT = 300; // 设置新的宽度
    int heightT = 100; // 设置新的高度
    QPixmap scaledPixmapT = titlePixmap.scaled(widthT, heightT, Qt::KeepAspectRatio);
    QPalette paletteT;
    paletteT.setBrush(QPalette::Background, scaledPixmapT);
    title->setAutoFillBackground(true);
    title->setPalette(paletteT);

    //首页界面添加书签图标
    QPixmap itemPixmap(":/icons/images/item1.png"); // 替换为你的图片路径
    // 调整图片尺寸
    int widthI = 50; // 设置新的宽度
    int heightI = 50; // 设置新的高度
    QPixmap scaledPixmapI = itemPixmap.scaled(widthI, heightI, Qt::KeepAspectRatio);
    QPalette paletteI;
    paletteI.setBrush(QPalette::Background, scaledPixmapI);
    QList<QLabel *> labelList;
    labelList << ui->item1 << ui->item2 << ui->item3 << ui->item4;
    foreach (QLabel *label, labelList) {
        label->setAutoFillBackground(true);
        label->setPalette(paletteI);
    }

    //首页界面添加标签图标
    /*QPixmap labelPixmap(":/icons/images/llabel.png"); // 替换为你的图片路径
    // 调整图片尺寸
    int widthl = 500; // 设置新的宽度
    int heightl = 64; // 设置新的高度
    QPixmap scaledPixmapl = labelPixmap.scaled(widthl, heightl, Qt::KeepAspectRatio);
    QPalette palettel;
    paletteI.setBrush(QPalette::Background, scaledPixmapl);
    QList<QLabel *> labelListl;
    labelListl << ui->label_language << ui->label_voice << ui->label_engine;
    foreach (QLabel *label, labelListl) {
        label->setAutoFillBackground(true);
        label->setPalette(paletteI);
    }*/

    //声音选择界面中pyttsx3,微软和谷歌的图标
    QLabel *microsoft = ui->micosoftIcon;
    QLabel *google = ui->googleIcon;
    QLabel *python = ui->pythonIcon;
    QLabel *baidu = ui->baiduIcon;
    QLabel *aliyun = ui->aliyunIcon;
    QPixmap microPixmap(":/icons/images/microsoft.png");
    QPixmap googlePixmap(":/icons/images/google.png");
    QPixmap pythonPixmap(":/icons/images/python.png");
    QPixmap baiduPixmap(":/icons/images/baidu.png");
    QPixmap aliyunPixmap(":/icons/images/aliyun.png");
    int width2 = 80;
    int height2 = 80;
    int widthp = 90;
    int heightp = 90;
    int widtha = 76;
    int heighta = 90;
    QPixmap scaledPixmap1 = microPixmap.scaled(width2, height2, Qt::KeepAspectRatio);
    QPixmap scaledPixmap2 = googlePixmap.scaled(width2, height2, Qt::KeepAspectRatio);
    QPixmap scaledPixmap3 = pythonPixmap.scaled(widthp, heightp, Qt::KeepAspectRatio);
    QPixmap scaledPixmapb = baiduPixmap.scaled(width2, height2, Qt::KeepAspectRatio);
    QPixmap scaledPixmapa = aliyunPixmap.scaled(widtha, heighta, Qt::KeepAspectRatio);
    QPalette palette1;
    QPalette palette2;
    QPalette palettep;
    QPalette paletteb;
    QPalette palettea;
    palette1.setBrush(QPalette::Background, scaledPixmap1);
    palette2.setBrush(QPalette::Background, scaledPixmap2);
    palettep.setBrush(QPalette::Background, scaledPixmap3);
    paletteb.setBrush(QPalette::Background, scaledPixmapb);
    palettea.setBrush(QPalette::Background, scaledPixmapa);
    microsoft->setAutoFillBackground(true);
    google->setAutoFillBackground(true);
    python->setAutoFillBackground(true);
    baidu->setAutoFillBackground(true);
    aliyun->setAutoFillBackground(true);
    microsoft->setPalette(palette1);
    google->setPalette(palette2);
    python->setPalette(palettep);
    baidu->setPalette(paletteb);
    aliyun->setPalette(palettea);

    //声音选择界面中聊天框的图标
    QLabel *voiceDesc = ui->voiceDescription;
    QPixmap descPixmap(":/icons/images/chat.png");
    int width3 = 460;
    int height3 = 320;
    QPixmap scaledPixmapDesc = descPixmap.scaled(width3, height3, Qt::KeepAspectRatio);
    QPalette palette3;
    palette3.setBrush(QPalette::Background, scaledPixmapDesc);
    voiceDesc->setAutoFillBackground(true);
    voiceDesc->setPalette(palette3);

    //快捷键说明界面
    QPixmap llPixmap(":/icons/images/longLabel.png");
    int widthll = 360;
    int heightll = 140;
    QPixmap scaledPixmapll = llPixmap.scaled(widthll, heightll, Qt::KeepAspectRatio);
    QPalette palettell;
    palettell.setBrush(QPalette::Background, scaledPixmapll);
    QList<QLabel *> labelListll;
    labelListll << ui->label_shortcut1 << ui->label_shortcut2 << ui->label_shortcut3 << ui->label_shortcut4 << ui->label_shortcut5 << ui->label_shortcut6 << ui->label_shortcut7;
    foreach (QLabel *label, labelListll) {
        label->setAutoFillBackground(true);
        label->setPalette(palettell);
    }

}

//style function: 实现渐变效果
void MainWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    // 在 paintEvent 中绘制渐变背景
    QPainter painter(this);
    // 创建渐变对象
    QLinearGradient gradient(0, 0, 0, height());
    switch(nowTheme)
        {
            case 0:
                gradient.setColorAt(0, Qt::lightGray);
                gradient.setColorAt(1, Qt::darkGray);
                break;
            case 1:
                gradient.setColorAt(0, Qt::white);
                gradient.setColorAt(1, Qt::lightGray);
                break;
            case 2:
                gradient.setColorAt(0, Qt::darkGray);
                gradient.setColorAt(1, Qt::lightGray);
                break;
            case 3:
                gradient.setColorAt(0, Qt::white);
                gradient.setColorAt(1, Qt::white);
                break;
            case 4:
                gradient.setColorAt(0, Qt::white);
                gradient.setColorAt(1, Qt::white);
                break;
            case 5:
                gradient.setColorAt(0, Qt::lightGray);
                gradient.setColorAt(1, Qt::darkGray);
                break;
        break;
            default:
                // 默认操作，如果选择了未处理的项
                break;
        }
    // 使用渐变填充背景
    painter.fillRect(rect(), QBrush(gradient));
}

//slot function: 切换全局样式
void MainWindow::onComboBoxIndexChanged(int index)
{
    nowTheme = index;
    QString style = GlobalStyle::getInstance().getStyle(nowTheme, fontSize);
    MainWindow::setStyleSheet(style);
    playAudio();
    showTextBox();
    if(fontSize == 3)
        showBigTextBox();
}

//slot function: 根据列表项的索引切换到相应的子页面
void MainWindow::on_menuList_currentRowChanged(int currentRow)
{
    ui->pages->setCurrentIndex(currentRow);
}

//tts-slot:
void MainWindow::checkSlot1(bool flag)
{
    if(flag==true)
    {
        ttsMode = 1;
        ui->label_engine->setText("pyttsx3");
    }
}
void MainWindow::checkSlot2(bool flag)
{
    if(flag==true)
    {
        ttsMode = 2;
        ui->label_engine->setText("微软");
    }
}
void MainWindow::checkSlot3(bool flag)
{
    if(flag==true)
    {
        QMessageBox::information(this,
            tr("谷歌语音"),
            tr("谷歌语音需要在vpn联网环境下使用。"),
            QMessageBox::Ok | QMessageBox::Cancel,
            QMessageBox::Ok);
        ttsMode = 3;
        ui->label_engine->setText("谷歌");
    }
}
void MainWindow::checkSlot4(bool flag)
{
    if(flag==true)
    {
        ttsMode = 4;
        ui->label_engine->setText("百度");
    }
}
void MainWindow::checkSlot5(bool flag)
{
    if(flag==true)
    {
        ttsMode = 5;
        ui->label_engine->setText("阿里云");
    }
}
//导入python模块
void MainWindow::importPythonModules()
{
    //DetectionScript.py模块
    pModule1 = PyImport_ImportModule("DetectionScript");
    if (!pModule1) {
        PyErr_Print(); // 输出详细错误信息
    }
    //RecognizitionScript.py模块
    pModule2 = PyImport_ImportModule("RecognizitionScript");
    if (!pModule2) {
        PyErr_Print();
    }
    //微软tts.py模块
    tts = PyImport_ImportModule("tts");
    if (!tts) {
        PyErr_Print();
    }
    //pyttsx3Script.py模块
    pyttsx3 = PyImport_ImportModule("pyttsx3Script");
    if (!pyttsx3) {
        PyErr_Print();
    }
    gtts  = PyImport_ImportModule("gttsScript");
    if (!gtts) {
        PyErr_Print();
    }
    //Audio.py模块
    audio = PyImport_ImportModule("Audio");
    if (!audio) {
        PyErr_Print(); // 输出详细错误信息
    }
    // aliyun.py(ai-spark)
    spark = PyImport_ImportModule("aliyun");
    if (!spark) {
        PyErr_Print(); // 输出详细错误信息
    }
}

//导入python方法
void MainWindow::importPythonFunctions()
{
    pDeteImport = PyObject_GetAttrString(pModule1,"DetectionPipelines");
    if(!pDeteImport){
        PyErr_Print();
    }
    pRecoImport = PyObject_GetAttrString(pModule2,"RecognizitionPipelines");
    if(!pRecoImport){
        PyErr_Print();
    }
    pDeteOcr = PyObject_GetAttrString(pModule1,"runDetection");
    if(!pDeteOcr){
        PyErr_Print();
    }
    pRecoOcr = PyObject_GetAttrString(pModule2,"runRecognizition");
    if(!pRecoOcr){
        PyErr_Print();
    }
    changeText = PyObject_GetAttrString(tts,"changeText");
    if(!changeText){
        PyErr_Print();
    }
    changeRate = PyObject_GetAttrString(tts,"changeRate");
    if(!changeRate){
        PyErr_Print();
    }
    changePitch = PyObject_GetAttrString(tts,"changePitch");
    if(!changePitch){
        PyErr_Print();
    }
    changeVoice = PyObject_GetAttrString(tts,"changeVoice");
    if(!changeVoice){
        PyErr_Print();
    }
    speak_microsoft = PyObject_GetAttrString(tts,"speak");
    if(!speak_microsoft){
        PyErr_Print();
    }
    setPyttsx3 = PyObject_GetAttrString(pyttsx3,"getVoices");
    if(!setPyttsx3){
        PyErr_Print();
    }
    speak_pyttsx3 = PyObject_GetAttrString(pyttsx3,"speak");
    if(!speak_pyttsx3){
        PyErr_Print();
    }
    speak_gtts = PyObject_GetAttrString(gtts,"speak");
    if(!speak_gtts){
        PyErr_Print();
    }
    generateMp3 = PyObject_GetAttrString(tts,"generateAudio");
    if(!generateMp3){
        PyErr_Print();
    }
    speak_baidu = PyObject_GetAttrString(gtts,"play");
    if(!speak_baidu){
        PyErr_Print();
    }
    aiResponse = PyObject_GetAttrString(spark,"response");
    if(!aiResponse){
        PyErr_Print();
    }
    pAudioImport = PyObject_GetAttrString(audio,"AudioPipelines");
    if(!pAudioImport){
        PyErr_Print();
    }
    pAudioRecognize = PyObject_GetAttrString(audio,"AudioRecognize");
    if(!pAudioRecognize){
        PyErr_Print();
    }
    currentDate = PyObject_GetAttrString(audio,"get_current_date");
    if(!currentDate){
        PyErr_Print();
    }
    currentWeekday = PyObject_GetAttrString(audio,"get_current_weekday");
    if(!currentWeekday){
        PyErr_Print();
    }
    currentTime = PyObject_GetAttrString(audio,"get_current_time");
    if(!currentTime){
        PyErr_Print();
    }
    currentWeather = PyObject_GetAttrString(audio,"get_current_weather");
    if(!currentWeather){
        PyErr_Print();
    }
}

//为每个控件安装事件过滤器
void MainWindow::installFilter()
{
    QList<QLabel*> labelList = MainWindow::findChildren<QLabel*>();
    for (QLabel* label : labelList) {
        label->installEventFilter(this);
    }
    QList<QPushButton*> buttonList = MainWindow::findChildren<QPushButton*>();
    for (QPushButton* button : buttonList) {
        button->installEventFilter(this);
    }
}

//朗读文本-microsoft version
void MainWindow::microsoftSpeak()
{
    PyObject_CallObject(speak_microsoft, NULL);
}
//朗读文本-google version
void MainWindow::googleSpeak(QString text)
{
    QString language;
    PyObject* arg1 = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    if(ui->comboBox_google->currentIndex() == 0)
        language = "zh-cn";
    else
        language = "en";
    PyObject* arg2 = PyUnicode_DecodeUTF8(language.toUtf8().constData(), strlen(language.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(2, arg1, arg2);

    PyObject_CallObject(speak_gtts, args);
    Py_DECREF(args);
}
//朗读文本-pyttsx3 version
void MainWindow::pyttsSpeak(QString text)
{
    QString voice = ui->comboBox_pyttsx3->currentText();
    PyObject* arg1 = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    PyObject* arg2 = PyUnicode_DecodeUTF8(voice.toUtf8().constData(), strlen(voice.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(2, arg1, arg2);
    PyObject_CallObject(speak_pyttsx3, args);
}
//朗读文本-baidu version
void MainWindow::baiduSpeak(QString text, QString type, QString rate, QString pitch, QString volume, QString format)
{
    switch (ui->comboBox_baidu->currentIndex()) {
    case 0:
        type = "0";
        break;
    case 1:
        type = "1";
        break;
    case 2:
        type = "3";
        break;
    case 3:
        type = "4";
        break;
    case 4:
        type = "5";
        break;
    case 5:
        type = "103";
        break;
    case 6:
        type = "106";
        break;
    case 7:
        type = "110";
        break;
    case 8:
        type = "111";
        break;
    default:
        break;
    }
    PyObject* arg1 = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    PyObject* arg2 = PyUnicode_DecodeUTF8(type.toUtf8().constData(), strlen(type.toUtf8().constData()), "strict");
    rate = QString::number(ui->baidu_rate->value() / 7);
    PyObject* arg3 = PyUnicode_DecodeUTF8(rate.toUtf8().constData(), strlen(rate.toUtf8().constData()), "strict");
    pitch = QString::number(ui->baidu_pitch->value() / 7);
    PyObject* arg4 = PyUnicode_DecodeUTF8(pitch.toUtf8().constData(), strlen(pitch.toUtf8().constData()), "strict");
    volume = QString::number(ui->baidu_volume->value() / 11);
    PyObject* arg5 = PyUnicode_DecodeUTF8(volume.toUtf8().constData(), strlen(volume.toUtf8().constData()), "strict");
    PyObject* arg6 = PyUnicode_DecodeUTF8(format.toUtf8().constData(), strlen(format.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(6, arg1, arg2, arg3, arg4, arg5, arg6);
    PyObject_CallObject(speak_baidu, args);
    player->setMedia(QUrl::fromLocalFile("/home/mhc/result.mp3"));
    player->play();
}
//朗读文本-aliyun version
void MainWindow::aliyunSpeak(QString text)
{
    QString voice;
    switch (ui->comboBox_aliyun->currentIndex()) {
    case 0:
        voice = "xiaoyun";
        break;
    case 1:
        voice = "aimei";
        break;
    case 2:
        voice = "xiaoxian";
        break;
    case 3:
        voice = "zhixiaobai";
        break;
    case 4:
        voice = "zhixiaoxia";
        break;
    case 5:
        voice = "zhixiaomei";
        break;
    case 6:
        voice = "aishuo";
        break;
    case 7:
        voice = "zhifeng_emo";
        break;
    case 8:
        voice = "zhibing_emo";
        break;
    case 9:
        voice = "zhishuo";
        break;
    case 10:
        voice = "kenny";
        break;
    case 11:
        voice = "jielidou";
        break;
    case 12:
        voice = "taozi";
        break;
    case 13:
        voice = "aina";
        break;
    case 14:
        voice = "chuangirl";
        break;
    case 15:
        voice = "qingqing";
        break;
    case 16:
        voice = "cuijie";
        break;
    case 17:
        voice = "xiaoze";
        break;
    default:
        break;
    }
    QString rate = QString::number(ui->aliyun_rate->value() * 10 - 500);
    QString pitch = QString::number(ui->aliyun_pitch->value() * 10 - 500);
    QString volume = QString::number(ui->aliyun_rate->value());
    aliyuntts->aliyunPlay(text, voice, rate, pitch, volume);
}
//朗读文本
void MainWindow::speakText(QString text)
{
    if(ttsMode !=1 && ttsMode !=2 && ttsMode !=3 && ttsMode !=4 && ttsMode !=5)
        ttsMode = 5;
    switch (ttsMode) {
    case 1:
        pyttsSpeak(text);
        break;
    case 2:
        textChange(text);
        microsoftSpeak();
        break;
    case 3:
        googleSpeak(text);
        break;
    case 4:
        baiduSpeak(text);
        break;
    case 5:
        aliyunSpeak(text);
        break;
    default:
        break;
    }
}
//改变SSML.xml中的文本
void MainWindow::textChange(QString text)
{
    PyObject* arg = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject_CallObject(changeText, args);
    //Py_XDECREF(arg);
    //Py_XDECREF(args);
}

//展示语速的值
void MainWindow::updateratevalue(int value)
{
    //ui->rateSliderValue->setText(QString::number(value));
}
//展示音高的值
void MainWindow::updatepitchvalue(int value)
{
    //ui->pitchSliderValue->setText(QString::number(value));
}
//调节放大镜放大的倍数
void MainWindow::updatezoomvalue(int value)
{
    qDebug() << value;
    if (value <= 25)
        zoom = 2.0;
    else if (value <= 50)
        zoom = 3.0;
    else if (value <= 75)
        zoom = 4.0;
    else
        zoom = 6.0;
}

//Hoykeys-slots: 放大镜
void MainWindow::magnifierWindowSlot()
{
    if (!isMagnifierEnabled)
    {
        // 开启放大镜
        magnifier = new MagnifierWindow(NULL, zoom);
        magnifier->show();
        isMagnifierEnabled = true;
    }
    else
    {
        // 关闭放大镜
        delete magnifier;
        magnifier = nullptr;
        isMagnifierEnabled = false;
    }
}
//Hotkeys-slots: 将窗口正常化
void MainWindow::normalizeWindow()
{
    this->showNormal();
}
//Hotkeys-slots: 开始使用
void MainWindow::hotkeyStart()
{
    on_btnStart_clicked();
}
//Hotkeys-slots: 退出使用
void MainWindow::hotkeyQuit()
{
    QApplication::quit();
}
//Hoykeys-slots: 文本框
void MainWindow::showTextWindowSlots()
{
    if (!isTextWindowEnabled)
    {
        // 开启文本框
        on_showTextArea_clicked();
        isTextWindowEnabled = true;
    }
    else
    {
        // 关闭文本框
        on_showTextCancel_clicked();
        isTextWindowEnabled = false;
    }
}
//Hotkeys-slots: 复制正在识别的文字
void MainWindow::copyNowText()
{
    copyText(nowText);
}
//Hotkeys-slots: 快捷键打开麒麟百事通
void MainWindow::hotkeyAi()
{
    on_startAi_clicked();
}

void MainWindow::menulistItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    if(current != nullptr && enableAudioTips)
    {
        //textChange(current->text());
        //todo speakText();
    }
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    //鼠标进入
    if ((obj->inherits("QPushButton") || obj->inherits("QLabel")) && event->type() == QEvent::MouseButtonPress)
    {
        if(QPushButton *btn = qobject_cast<QPushButton*>(obj))
        {
            QString btntext = btn->text();
            if(enableAudioTips)
            {
                speakText(btntext);
            }
        }
        else if(QLabel *label = qobject_cast<QLabel*>(obj))
        {
            QString labeltext = label->text();
            if(enableAudioTips)
            {
                speakText(labeltext);
            }
        }
    }
    //鼠标离开
    else if ((obj->inherits("QPushButton") || obj->inherits("QLabel")) && event->type() == QEvent::Leave)
    {
        if (QPushButton* button = qobject_cast<QPushButton*>(obj))
        {
            //qDebug() << "Mouse left QPushButton: ";
        }
        else if (QLabel* label = qobject_cast<QLabel*>(obj))
        {
            //qDebug() << "Mouse left QLabel: ";
        }
    }
    return QMainWindow::eventFilter(obj, event);
}
//退出使用
void MainWindow::on_btnCancel_clicked()
{
    QApplication::quit();
}

//将导入两个模型的操作放在预处理中进行,测试容忍值的临界值，提高软件开启的速度
void MainWindow::preHandle()
{
    //调用pDeteImport函数,用来导入文本检测,文本识别的模型
    /*PyObject_CallFunction(pDeteImport,NULL);
    PyObject_CallFunction(pRecoImport,NULL);
    preHandleTimer->stop();
    delete preHandleTimer;*/
}
//开始使用
void MainWindow::on_btnStart_clicked()
{
    showMinimized();

    cutimage->captureNowFullScreen();
    cutimage->captureLastFullScreen();

    //ocr-detection
    PyObject* pResultD = PyObject_CallObject(pDeteOcr,NULL);
    if(pResultD) {
        //将返回值转化为string类型
        PyObject* reprD = PyObject_Repr(pResultD);
        PyObject* strD = PyUnicode_AsEncodedString(reprD, "utf-8", "strict");
        QString resultD = PyBytes_AsString(strD);
        GlobalArray::getInstance().setArray(resultD);
        Py_XDECREF(pResultD);  // 释放Python对象
    } else {
        PyErr_Print();
    }

    ocrTimer->start(3800);
    posTimer->start(600);
    PyGC_Collect();
}

//python-microsoft-tts

/*设置语速-1.0到1.0*/
void MainWindow::setRate(int rate)
{
    qDebug() << rate;
    PyObject* arg = PyLong_FromLong(rate);
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject_CallObject(changeRate, args);
}
/*设置音高-1.0到1.0*/
void MainWindow::setPitch(int pitch)
{
    qDebug() << pitch;
    PyObject* arg = PyLong_FromLong(pitch);
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject_CallObject(changePitch, args);
}
/*选择声音*/
void MainWindow::onvoicechange(int value)
{
    qDebug() << value;
    PyObject* arg = PyLong_FromLong(value);
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject_CallObject(changeVoice, args);
    QComboBox *voicechange = ui->comboBox_microsoft;
    QString text1 = voicechange->currentText();
    QString text2 = "您好，我是";
    speakText(text2 + text1);
    ui->label_voice->setText(text1);
}

void MainWindow::mouseInText()
{
    nowPos = QCursor::pos();
    temptVector = GlobalArray::getInstance().isTextIn(nowPos.x(), nowPos.y());
    if(!(temptVector.isEmpty()) && temptVector != textVector)
    {
        qDebug() << "hh";
        textVector = temptVector;
        cutimage->captureTextPosition(textVector);
        PyObject* pResultR = PyObject_CallObject(pRecoOcr,NULL);
        if(pResultR) {
            //将返回值转化为string类型
            PyObject* reprR = PyObject_Repr(pResultR);
            PyObject* strR = PyUnicode_AsEncodedString(reprR, "utf-8", "strict");
            QString resultR = PyBytes_AsString(strR);
            int length = resultR.length();
            QString text = resultR.mid(12, length-15).remove("\\").remove("'");
            qDebug() << text;
            nowText = text;
            speakText(text);
            Py_XDECREF(pResultR);  // 释放Python对象
        } else {
            PyErr_Print();
        }
    }
}

void MainWindow::handleImgChange()
{
   if (cutimage->compareImages(tolerance))
   {
       qDebug() << "界面内容没有发生变化";
       cutimage->captureLastFullScreen();
   }
   else
   {
       qDebug() << "界面内容发生了变化";
       cutimage->captureNowFullScreen();
       cutimage->captureLastFullScreen();

       //ocr-detection
       PyObject* pResultD = PyObject_CallObject(pDeteOcr,NULL);
       if(pResultD) {
           //将返回值转化为string类型
           PyObject* reprD = PyObject_Repr(pResultD);
           PyObject* strD = PyUnicode_AsEncodedString(reprD, "utf-8", "strict");
           QString resultD = PyBytes_AsString(strD);
           GlobalArray::getInstance().setArray(resultD);
           Py_XDECREF(pResultD);  // 释放Python对象
       } else {
           PyErr_Print();
       }
   }
}

//调用python脚本来实现微软tts功能
/*TextToSpeechTask::TextToSpeechTask(const QString& text)
    : m_text(text)
{
}
void TextToSpeechTask::run()
{
    try {
        // 这里放入调用 Python 脚本的代码来优化交互体验
        //qDebug() << "TextToSpeechTask: " << m_text;
        TextToSpeech *texttospeech = new TextToSpeech();
        texttospeech->speak(m_text);
    } catch (const QString& errorMsg) {
        qDebug() << errorMsg;
    }
}*/

//设置小号字体
void MainWindow::on_setSmallFont_clicked()
{
    fontSize = 0;
    int currentIndex = ui->comboBoxStyle->currentIndex();
    QString style = GlobalStyle::getInstance().getStyle(currentIndex, fontSize);
    MainWindow::setStyleSheet(style);
    playAudio();
    showTextBox();
}
//设置中号字体
void MainWindow::on_setMiddleFont_clicked()
{
    fontSize = 1;
    int currentIndex = ui->comboBoxStyle->currentIndex();
    QString style = GlobalStyle::getInstance().getStyle(currentIndex, fontSize);
    MainWindow::setStyleSheet(style);
    playAudio();
    showTextBox();
}
//设置大号字体
void MainWindow::on_setBigFont_clicked()
{
    fontSize = 2;
    int currentIndex = ui->comboBoxStyle->currentIndex();
    QString style = GlobalStyle::getInstance().getStyle(currentIndex, fontSize);
    MainWindow::setStyleSheet(style);
    playAudio();
    showTextBox();
}

//保存音频文件
void MainWindow::on_generateButton_clicked()
{
    QString text = ui->audioText->toPlainText();
    audioPath = ui->audioPath->text();

    QMessageBox::information(this,
        tr("保存音频"),
        tr("音频保存成功!"),
        QMessageBox::Ok | QMessageBox::Cancel,
        QMessageBox::Ok);

    ui->audioText->setText("");
}
void MainWindow::on_generateButton_listen_clicked()
{
    player->setMedia(QUrl::fromLocalFile(audioPath));
    player->play();
}
/*tools functions*/
//开启语音提示功能
void MainWindow::on_setPlayVisible_clicked()
{
    enableAudioTips = true;
    /*foreach (QLabel *label, audioLogoList) {
        label->setVisible(true);
    }*/
}
//关闭语音提示功能
void MainWindow::on_setPlayInvisible_clicked()
{
    enableAudioTips = false;
    foreach (QLabel *label, audioLogoList) {
        label->setVisible(false);
    }
}
//切换鼠标样式
void MainWindow::on_changeCursor_clicked()
{
    // 初始化随机数生成器
    QTime time = QTime::currentTime();
    qsrand(static_cast<uint>(time.msec()));
    int randomNumber = qrand() % 6; // 范围为0到5
    switch (randomNumber) {
        case 0:
            QApplication::setOverrideCursor(QCursor(Qt::WhatsThisCursor));
          break;
        case 1:
            QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
          break;
        case 2:
            QApplication::setOverrideCursor(QCursor(Qt::SizeAllCursor));
          break;
        case 3:
            QApplication::setOverrideCursor(QCursor(Qt::OpenHandCursor));
          break;
        case 4:
            QApplication::setOverrideCursor(QCursor(Qt::OpenHandCursor));
          break;
        case 5:
            QApplication::setOverrideCursor(QCursor(Qt::OpenHandCursor));
          break;
        default:
          break;
    }
}
//默认鼠标样式
void MainWindow::on_recoverCursor_clicked()
{
    // 恢复默认鼠标光标
    QApplication::restoreOverrideCursor();
}
//绘制文本框
void MainWindow::on_showTextArea_clicked()
{
    cutimage->captureNowFullScreen();
    //处理全屏截图获得文字框的坐标值
    PyObject* pResultD = PyObject_CallObject(pDeteOcr,NULL);
    if(pResultD) {
        //将返回值转化为string类型
        PyObject* reprD = PyObject_Repr(pResultD);
        PyObject* strD = PyUnicode_AsEncodedString(reprD, "utf-8", "strict");
        QString resultD = PyBytes_AsString(strD);
        //qDebug() << resultD;
        GlobalArray::getInstance().setArray(resultD);
        Py_XDECREF(pResultD);  // 释放Python对象
    } else {
        PyErr_Print();
    }
    QVector<QVector<int>> array = GlobalArray::getInstance().getArray();
    // 绘制文本框
    textwindow = new ShowTextWindow();
    textwindow->setRectangles(array);
    textwindow->show();
    isTextWindowEnabled = true;
}
//取消显示文本框
void MainWindow::on_showTextCancel_clicked()
{
    // 关闭放大镜
    delete textwindow;
    textwindow = nullptr;
    isTextWindowEnabled = false;
}

//保存个性化设置
void MainWindow::on_rememberSettings_clicked()
{
    //用来说明每一项对应的配置
    int themeStyle = ui->comboBoxStyle->currentIndex();
    int voiceStyle;
    if (ttsMode == 1)
        voiceStyle = ui->comboBox_pyttsx3->currentIndex();
    else if (ttsMode == 2)
        voiceStyle = ui->comboBox_microsoft->currentIndex();
    else if (ttsMode == 3)
        voiceStyle = ui->comboBox_google->currentIndex();
    else if (ttsMode == 4)
        voiceStyle = ui->comboBox_baidu->currentIndex();
    else if (ttsMode == 5)
        voiceStyle = ui->comboBox_aliyun->currentIndex();
    else {
        ttsMode = 2;
        voiceStyle = 0;
    }
    int rateValue = ui->slider_rate->value();
    int pitchValue = ui->slider_pitch->value();
    int AudioStyle;
    if (fontSize != 0 && fontSize != 1 && fontSize != 2)
        fontSize = 1;
    if (enableAudioTips)
        AudioStyle = 1;
    else
        AudioStyle = 0;
    QString path = ui->audioPath->text();

    // 创建一个QFile对象并打开文本文件
   QFile file("/home/mhc/settings.txt");
   if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
       qDebug() << "无法打开文件";
   }

   // 创建一个QTextStream对象并关联到文件
   QTextStream out(&file);

   // 保存个性化配置
   out << themeStyle << endl;
   out << QString::number(ttsMode) << endl;
   out << QString::number(voiceStyle) << endl;
   out << QString::number(rateValue) << endl;
   out << QString::number(pitchValue) << endl;
   out << QString::number(AudioStyle) << endl;
   out << QString::number(fontSize) << endl;
   out << path << endl;
   //out << zoom << endl;

   // 关闭文件
   file.close();
}
//恢复默认配置
void MainWindow::on_defaultSettings_clicked()
{
    //默认不开启语音提示功能
    on_setPlayInvisible_clicked();
    zoom = 4.0;
    //默认设置女声晓晓，语速0，语调0
    onvoicechange(0);
    updateratevalue(0);
    updatepitchvalue(0);
    //加载界面
    fontSize = 1;
    ui->radioButton_microsoft->setChecked(true);
    ttsMode = 2;
    QString styleSheet = GlobalStyle::getInstance().getStyle(0, fontSize);
    MainWindow::setStyleSheet(styleSheet);

    ui->slider_rate->setValue(10);
    ui->slider_pitch->setValue(10);

    // 获取当前应用程序的工作目录,作为默认的音频生成地址
    QString currentDir = QDir::currentPath();
    QString defaultName = "/test.mp3";
    ui->audioPath->setText(currentDir+defaultName);
    QString text;
    switch (ttsMode) {
    case 1:
        text = ui->comboBox_pyttsx3->currentText();
        ui->label_voice->setText(text);
        break;
    case 2:
        text = ui->comboBox_microsoft->currentText();
        ui->label_voice->setText(text);
        break;
    case 3:
        text = ui->comboBox_google->currentText();
        ui->label_voice->setText(text);
        break;
    default:
        break;
    }
    menuIcon();
    showTextBox();
    playAudio();
    connectSlots();
}

// 一键复制
void MainWindow::copyText(QString text)
{
    // 获取应用程序剪贴板
    QClipboard *clipboard = QGuiApplication::clipboard();
    // 复制文本到剪贴板
    clipboard->setText(text);
}

// 工具界面中打开AI-麒麟百事通
void MainWindow::on_startAi_clicked()
{
    if(aidialog){
        aidialog = nullptr;
    }
    aidialog = new AiDialog(this);
    connectSlots();
    aidialog->show();
    QScreen *primaryScreen = QGuiApplication::primaryScreen();
    // 获取屏幕的尺寸
    QSize screenSize = primaryScreen->size();
    // 规范小麒麟图标的出现位置
    aidialog->move(screenSize.width()/2 + this->size().width()/2, screenSize.height()/2 - aidialog->size().height()/2);
}

// 录音
void MainWindow::audioRecorder()
{
    recorder->setContainerFormat("audio/x-wav");
    recorder->setOutputLocation(QUrl::fromLocalFile("/home/mhc/out.wav"));
    recorder->setAudioInput(recorder->defaultAudioInput());
    recorder->record();
}

// 语音识别
QString MainWindow::audioToText()
{
    PyObject* pResult = PyObject_CallObject(pAudioRecognize,NULL);
    if(pResult) {
        //将返回值转化为string类型
        PyObject* repr = PyObject_Repr(pResult);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
        QString result = PyBytes_AsString(str);
        result = result.mid(10, result.length() - 12);
        qDebug() << result;
        return result;
        Py_XDECREF(pResult);  // 释放Python对象
    } else {
        PyErr_Print();
        qDebug() << "调用语音识别脚本出错";
        return "";
    }
}

// 人工智能
void MainWindow::stopRecorder()
{
    recorder->stop();
    QString text = audioToText();
    aidialog->showQuestion(text);
    PyObject* arg = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject* pResult = PyObject_CallObject(aiResponse, args);
    if(pResult) {
        //将返回值转化为string类型
        PyObject* repr = PyObject_Repr(pResult);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
        QString result = PyBytes_AsString(str);
        qDebug() << result;
        aidialog->showAnswer(result);
        Py_XDECREF(pResult);  // 释放Python对象
    } else {
        PyErr_Print();
        qDebug() << "调用脚本出错";
    }
    Py_XDECREF(args);

    //duchulai caozuo
}

// 语音转文字拓展功能
void MainWindow::on_audioRecognize_pressed()
{
    ui->audioToText->setText("");
    audioRecorder();
}
// 松开按钮录制完毕并进行识别
void MainWindow::on_audioRecognize_released()
{
    recorder->stop();
    QString text = audioToText();
    ui->audioToText->setText(text);
}
// 一键复制所有文本
void MainWindow::on_copyText_clicked()
{
    copyText(ui->audioToText->toPlainText());
}

void MainWindow::startAssistant()
{
    dialog->show();
    dialog->move(this->pos().x() + this->size().width(), this->pos().y());

    audioAssistant();
    audioTimer->start();
}

// 语音助手录音
void MainWindow::audioAssistant()
{
    //dialog->changeToImg();
    audioRecorder();
    const int duration = 3200;
    QTimer::singleShot(duration, [this]() {
        recorder->stop();
        QString text = audioToText();
        dialog->changeToText(text);
        dialog->audioToFunction(text);
    });
}

// 停止循环录音操作
void MainWindow::stopTimer()
{
    audioTimer->stop();
}

// 连接自定义的信号的槽函数
void MainWindow::call()
{
    speakText("我在，有什么可以帮助您");
}
void MainWindow::changeThemeToBw()
{
    onComboBoxIndexChanged(0);
}
void MainWindow::stopAi()
{
    aidialog->close();
}
void MainWindow::myCheckSlot1()
{
    checkSlot1(true);
}
void MainWindow::myCheckSlot2()
{
    checkSlot2(true);
}
void MainWindow::myCheckSlot3()
{
    checkSlot3(true);
}
void MainWindow::myCheckSlot4()
{
    checkSlot4(true);
}
void MainWindow::myCheckSlot5()
{
    checkSlot5(true);
}
// 工具界面中关闭AI-麒麟百事通
void MainWindow::on_stopAi_clicked()
{
    if(aidialog)
    {
        aidialog->close();
        aidialog = nullptr;
    }
}
// 工具界面中打开语音助手
void MainWindow::on_startAssistantLogo_clicked()
{
    if(logo){
        logo->close();
        logo = nullptr;
    }
    if(dialog){
        dialog->close();
        dialog = nullptr;
    }
    stopRecorder();
    logo = new AudioLogo(this);
    dialog = new CustomDialog(this);
    connectSlots();
    logo->show();
    QScreen *primaryScreen = QGuiApplication::primaryScreen();
    // 获取屏幕的尺寸
    QSize screenSize = primaryScreen->size();
    // 规范小麒麟图标的出现位置
    logo->move(screenSize.width()/2 + this->size().width()/2, screenSize.height()/2 - logo->size().height()/2);
}
// 工具界面中关闭语音助手
void MainWindow::on_stopAssisantLogo_clicked()
{
    if(logo){
        logo->close();
        logo = nullptr;
    }
    if(dialog){
        dialog->close();
        dialog = nullptr;
    }
    stopRecorder();
}

// 用来更新首页中语速，音高和音量标签的值
void MainWindow::updateLabelValue()
{
    if(ttsMode == 1 || ttsMode == 3)
    {
        ui->label_rate_value->setText("正常");
        ui->label_pitch_value->setText("正常");
        ui->label_volume_value->setText("正常");
    } else if (ttsMode == 2) {
        ui->label_rate_value->setText(QString::number(ui->slider_rate->value()));
        ui->label_pitch_value->setText(QString::number(ui->slider_pitch->value()));
        ui->label_volume_value->setText("正常");
    } else if (ttsMode == 4) {
        ui->label_rate_value->setText(QString::number(ui->baidu_rate->value()));
        ui->label_pitch_value->setText(QString::number(ui->baidu_pitch->value()));
        ui->label_volume_value->setText(QString::number(ui->baidu_volume->value()));
    } else {
        ui->label_rate_value->setText(QString::number(ui->aliyun_rate->value()));
        ui->label_pitch_value->setText(QString::number(ui->aliyun_pitch->value()));
        ui->label_volume_value->setText(QString::number(ui->aliyun_volume->value()));
    }
}

void MainWindow::speakAiAnswer()
{
    QString text = aidialog->getText();
    speakText(text);
}

// 获取每个组件，放大
// 对所有的子控件以相同的放缩因子进行放缩
void MainWindow::getAllWidgets(QWidget *widget, float zoomFactor) {
    // 获取当前控件的所有子控件
    QList<QWidget*> childWidgets = widget->findChildren<QWidget*>();

    // 定义需要排除的类型
    /*const QMetaObject* excludedType = &QListView::staticMetaObject; // 以QPushButton为例
    // 创建一个过滤后的列表，排除特定类型的控件
    QList<QWidget*> filteredChildWidgets;
    foreach (QWidget* widget, childWidgets) {
        if (widget->metaObject() != excludedType) {
            filteredChildWidgets.append(widget);
        }
    }*/

    foreach (QWidget* childWidget, childWidgets) {
        QPoint widgetPosition = childWidget->pos(); // 获取控件的相对位置
        QSize widgetSize = childWidget->size(); // 获取控件的尺寸

        childWidget->move(widgetPosition.x() * 1.10, widgetPosition.y() * 1.07);
        childWidget->resize(widgetSize.width() * 1.06, widgetSize.height() * 1.06);
        // 递归
        getAllWidgets(childWidget, zoomFactor);
    }
}

// 调整整个界面的大小
void MainWindow::on_bigWindow_clicked()
{
    float zoomFactor = 1.7;
    resize(this->size().width() * zoomFactor, this->size().height() * zoomFactor);

    //设置圆角
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.drawRoundedRect(bmp.rect(),20,20);//像素为10的圆角
    setMask(bmp);

    getAllWidgets(this, zoomFactor);
    ui->menuList->resize(ui->menuList->size().width() * 1.3, ui->menuList->size().height() * zoomFactor);

    // 让主界面在屏幕中心出现
    QScreen *primaryScreen = QGuiApplication::primaryScreen();
    // 获取屏幕的尺寸
    QSize screenSize = primaryScreen->size();
    this->move(screenSize.width()/2 - this->size().width()/2, screenSize.height()/2 - this->size().height()/2);
    // 规范小麒麟图标的出现位置
    logo->move(screenSize.width()/2 + this->size().width()/2, screenSize.height()/2 - logo->size().height()/2);

    // 手动对部分控件的位置进行微调
    ui->label_pitch->move(ui->label_pitch->x()*0.9, ui->label_pitch->y());
    ui->label_pitch_value->move(ui->label_pitch_value->x()*0.9, ui->label_pitch_value->y());
    ui->label_volume->move(ui->label_volume->x()*0.9, ui->label_volume->y());
    ui->label_volume_value->move(ui->label_volume_value->x()*0.9, ui->label_volume_value->y());
    QList<QLabel*> labelList1, labelList2;
    QList<QSlider*> sliderList;
    QList<QPushButton*> buttonList;
    labelList1 << ui->label_5 << ui->label_6 << ui->label_7 << ui->label_8 << ui->label_10 << ui->label_11;
    labelList2 << ui->label_9 << ui->label_12 << ui->label_13 << ui->label_14 << ui->label_15 << ui->label_16;
    sliderList << ui->slider_pitch << ui->baidu_volume_2 << ui->baidu_pitch << ui->baidu_volume << ui->aliyun_pitch << ui->aliyun_volume;
    buttonList << ui->setPlayInvisible << ui->bigWindow << ui->setMiddleFont << ui->setBigFont << ui->recoverCursor << ui->transToMooc << ui->transToHaoyanli << ui->transToQimingxing << ui->audioTime << ui->audioWeekday << ui->audioWeather << ui->showTextCancel << ui->stopAssisantLogo << ui->stopAi;
    foreach (QLabel* label, labelList1) {
        label->move(label->x() * 2, label->y());
    }
    foreach (QLabel* label, labelList2) {
        label->move(label->x() * 0.9, label->y());
    }
    foreach (QSlider* slider, sliderList) {
        slider->move(slider->x() * 0.9, slider->y());
    }
    foreach (QPushButton* button, buttonList) {
        button->move(button->x() * 0.9, button->y());
    }
    ui->audioText->move(ui->audioText->x()*1.7, ui->audioText->y());
    ui->audioText->resize(ui->audioText->width()*1.08, ui->audioText->height()*1.1);
    ui->label->move(ui->label->x()*1.7, ui->label->y());
    ui->generateButton->move(ui->generateButton->x()*1.7, ui->generateButton->y());
    ui->generateButton_listen->move(ui->generateButton_listen->x()*0.91, ui->generateButton_listen->y());
    ui->audioToText->move(ui->audioToText->x()*1.3, ui->audioToText->y()*1.18);
    ui->audioToText->resize(ui->audioToText->width()*1.15, ui->audioToText->height()*1.05);
    ui->audioRecognize->move(ui->audioRecognize->x()*1.28, ui->audioRecognize->y());
    ui->copyText->move(ui->copyText->x()*0.98, ui->copyText->y());
    // 放大字体和图标
    fontSize = 3;
    int currentIndex = ui->comboBoxStyle->currentIndex();
    QString style = GlobalStyle::getInstance().getStyle(currentIndex, fontSize);
    MainWindow::setStyleSheet(style);
    showBigTextBox();
}

// 网址导航
void MainWindow::transToUrl(QString urlPath)
{
    QUrl url(urlPath);
    if (QDesktopServices::openUrl(url)) {
        qDebug() << "URL opened successfully.";
    } else {
        qDebug() << "Failed to open the URL.";
    }
}
// 网址导航1：百度
void MainWindow::on_transToBaidu_clicked()
{
    transToUrl("https://www.baidu.com");
}
// 网址导航2：Mooc
void MainWindow::on_transToMooc_clicked()
{
    transToUrl("https://www.icourse163.org");
}
// 网址导航3：启明星
void MainWindow::on_transToQimingxing_clicked()
{
    transToUrl("http://www.qhqmx.com.cn");
}
// 网址导航4：好眼力
void MainWindow::on_transToHaoyanli_clicked()
{
    transToUrl("http://www.vsmvision.com");
}
// 语音播报
void MainWindow::on_audioDate_clicked()
{
    PyObject* pResult = PyObject_CallObject(currentDate,NULL);
    if(pResult) {
        //将返回值转化为string类型
        PyObject* repr = PyObject_Repr(pResult);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
        QString result = PyBytes_AsString(str);
        //qDebug() << result;
        speakText(result.mid(14, 4) + "年" + result.mid(20, 2) + "月" + result.mid(24) + "日");
        Py_XDECREF(pResult);  // 释放Python对象
    } else {
        PyErr_Print();
        qDebug() << "调用语音播报脚本出错";
    }
}
void MainWindow::on_audioWeekday_clicked()
{
    PyObject* pResult = PyObject_CallObject(currentWeekday,NULL);
    if(pResult) {
        //将返回值转化为string类型
        PyObject* repr = PyObject_Repr(pResult);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
        QString result = PyBytes_AsString(str);
        speakText("今天是" + result);
        Py_XDECREF(pResult);  // 释放Python对象
    } else {
        PyErr_Print();
        qDebug() << "调用语音播报脚本出错";
    }
}
void MainWindow::on_audioTime_clicked()
{
    PyObject* pResult = PyObject_CallObject(currentTime,NULL);
    if(pResult) {
        //将返回值转化为string类型
        PyObject* repr = PyObject_Repr(pResult);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
        QString result = PyBytes_AsString(str);
        qDebug() << result;
        speakText(result.mid(1, 2) + "时" + result.mid(4, 2) + "分" + result.mid(7) + "秒");
        Py_XDECREF(pResult);  // 释放Python对象
    } else {
        PyErr_Print();
        qDebug() << "调用语音播报脚本出错";
    }
}
void MainWindow::on_audioWeather_clicked()
{
    PyObject* pResult = PyObject_CallObject(currentWeather,NULL);
    if(pResult) {
        //将返回值转化为string类型
        PyObject* repr = PyObject_Repr(pResult);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
        QString result = PyBytes_AsString(str);
        speakText("当前温度" +result.mid(0, 4) + "当前湿度" + result.mid(5, 3) + "当前天气" + result.mid(10));
        Py_XDECREF(pResult);  // 释放Python对象
    } else {
        PyErr_Print();
        qDebug() << "调用语音播报脚本出错";
    }
}

MainWindow::~MainWindow()
{
    delete magnifier;
    delete magnifierKey;
    delete normalizeKey;
    delete cutimage;
    delete posTimer;
    delete ocrTimer;
    delete aliyuntts;
    delete player;
    delete recorder;
    delete aidialog;
    delete dialog;
    delete logo;
    delete AiKey;
    //ocr
    Py_XDECREF(pModule1);
    Py_XDECREF(pModule2);
    Py_XDECREF(pDeteImport);
    Py_XDECREF(pRecoImport);
    Py_XDECREF(pDeteOcr);
    Py_XDECREF(pRecoOcr);
    //tts
    Py_XDECREF(tts);
    Py_XDECREF(pyttsx3);
    Py_XDECREF(gtts);
    Py_XDECREF(speak_microsoft);
    Py_XDECREF(speak_gtts);
    Py_XDECREF(speak_pyttsx3);
    Py_XDECREF(changeText);
    Py_XDECREF(setPyttsx3);
    Py_XDECREF(speak_baidu);
    //audio
    Py_XDECREF(audio);
    Py_XDECREF(pAudioImport);
    Py_XDECREF(pAudioRecognize);
    Py_XDECREF(currentDate);
    Py_XDECREF(currentWeekday);
    Py_XDECREF(currentTime);
    Py_XDECREF(currentWeather);
    Py_Finalize();
    delete ui;
}
